package com.sny.controller;

import com.sny.constants.EcspConstants;
import com.sny.constants.FileConstants;
import com.sny.constants.Result;
import com.sny.constants.ResultForAmis;
import com.sny.dto.FileStorageDto;
import com.sny.dto.FileUploadDTO;
import com.sny.emun.ResponseMsg;
import com.sny.exception.BizException;
import com.sny.service.IFileService;
import com.sny.service.IFileStorageService;
import com.sny.util.*;
import com.sny.vo.param.FileUploadRequestParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.StopWatch;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author:yangxupeng
 * @Description:
 * @Date: 2020/7/30 2:41 下午
 * @Modified:
 */
// @RestController
@Controller
@RequestMapping(value = {"/api", "/FileService"})
@Slf4j
public class FileServiceController {

    @Value("${fms.application.file.path}")
    public String filePath;
    @Value("${fms.application.file.download.service.url}")
    private String fileServiceDownloadUrl;
    @Value("${fms.application.view.service.url}")
    private String preViewServiceUrl;
    @Value("${fms.application.view.flag}")
    public String preViewFlag;
    @Value("${fms.application.base64.file.path}")
    public String fileBase64Path;

    @Value("${upload.root.dir}")
    private String uploadRootDir;

    @Value("${upload.window.root}")
    private String uploadWindowRoot;

    // 特殊字符
    @Value("${upload.specialCharStr}")
    private String specialCharStr;

    @Autowired
    private IFileStorageService fileStorageService;
    @Autowired
    private IFileService fileService;

    @GetMapping(value = "/")
    public String gotoPage() {
        return "index";
    }

    @GetMapping(value = "/uploadFile")
    public String gotoFilePage() {
        return "upload";
    }

    @GetMapping(value = "/oss/upload")
    public String gotoOssPage() {
        return "ossUpload";
    }


    /**
     * 上传文件
     *
     * @param file        文件 file
     * @param loginName   上传用户登录名称
     * @param description 文件描述
     * @param appId       应用Id
     */
    @PostMapping("/upload")
    @ResponseBody
    public Result upload(@RequestParam("file") MultipartFile file, String loginName, String description, String isWaterMar, String appId, HttpServletResponse response) throws Exception {
        response.setContentType("text/html;charset=UTF-8");
        response.setHeader("Access-Control-Allow-Origin", "*");
        if (null != file) {
            String[] specialCharArr = specialCharStr.split(",");
            for (String specialChar : specialCharArr) {
                String originalFilename = file.getOriginalFilename();
                if (originalFilename.contains(specialChar)) {
                    return Result.success("fileStorage", FileConstants.FAILFILENAME, "文件名不合法，文件名不能包含"+ specialCharStr +"字符，请修改文件名，重新上传。");
                }
            }
            if (file.getSize() >= FileConstants.IMGSIZE) {
                return Result.success("fileStorage", FileConstants.FILESIZE, "上传文件超过限制大小");
            } else {
                StringBuffer sbPath = new StringBuffer();
                if (null != appId && !"".equals(appId)) {
                    sbPath.append(appId);
                } else if (null != loginName && !"".equals(loginName)) {
                    //用户名首字母
                    sbPath.append("/");
                    sbPath.append(loginName.substring(0, 1).toLowerCase());
                    sbPath.append("/");
                    //用户名
                    sbPath.append(loginName);
                } else {
                    sbPath.append("other");
                }
                sbPath.append("/");
                //拼接文件类型
                sbPath.append(FileUtil.getFileType(file.getOriginalFilename()));
                sbPath.append("/");
                String userPath = sbPath.toString();
                String filedirPath = filePath + userPath;
                //判断文件夹是否存在，如果不存在就创建
                FileUtil.isExist(filedirPath);
                //获取文件后缀
                String suffix = FileUtil.getFileSuffix(file.getOriginalFilename());
                //生成唯一文件名
                String uuId = CodecUtil.UUID();
                String fileName = uuId + suffix;
                File tofile = new File(filedirPath + fileName);
                file.transferTo(tofile);
                if ("img".equals(FileUtil.getFileType(file.getOriginalFilename()))) {
                    //文件服务水印逻辑去掉
                    FileUtil.imagesResize(tofile, filedirPath);

                }
                FileStorageDto fileStorage = new FileStorageDto();
                fileStorage.setName(uuId);
                fileStorage.setFilename(file.getOriginalFilename());
                fileStorage.setUrl(userPath);
                if (null != description && !"".equals(description)) {
                    fileStorage.setDescription(description);
                }
                fileStorage.setSize(file.getSize());
                fileStorage.setSuffix(suffix);
                fileStorage.setUserName(loginName);
                //将上传文件信息存入数据库
                fileStorage = this.fileStorageService.save(fileStorage);
                if (null != fileStorage) {
                    //判断是否需要转换在线预览服务
                    if ("Y".equals(preViewFlag)) {
                        if ("doc".equals(FileUtil.getFileType(file.getOriginalFilename()))) {
                            fileService.preViewTask(fileServiceDownloadUrl, preViewServiceUrl,
                                    fileStorage.getName(), FileUtil.getFileSuffix(file.getName()));
                        }
                    }
                    return Result.success("fileStorage", EcspConstants.SUCESS, "上传成功", fileStorage);
                } else {
                    return Result.success("fileStorage", FileConstants.STORAGEFAIL, "信息存储失败");
                }
            }
        } else {
            return Result.success("fileStorage", FileConstants.FILENOTNULL, "上传文件不能为空");
        }


    }

    /**
     * 上传文件
     *
     * @param file        文件 file
     * @param loginName   上传用户登录名称
     * @param description 文件描述
     * @param appId       应用Id
     */
    @PostMapping("/uploadForAmis")
    @ResponseBody
    public ResultForAmis uploadForAmis(@RequestParam("file") MultipartFile file, String loginName, String description, String isWaterMar, String appId, HttpServletResponse response) throws Exception {
        response.setContentType("text/html;charset=UTF-8");
        response.setHeader("Access-Control-Allow-Origin", "*");
        if (null != file) {
            String[] specialCharArr = specialCharStr.split(",");
            for (String specialChar : specialCharArr) {
                String originalFilename = file.getOriginalFilename();
                if (originalFilename.contains(specialChar)) {
                    return ResultForAmis.fail( "文件名不合法，文件名不能包含"+ specialCharStr +"字符，请修改文件名，重新上传。");
                }
            }
            if (file.getSize() >= FileConstants.IMGSIZE) {
                return ResultForAmis.fail("上传文件超过限制大小");
            } else {
                StringBuffer sbPath = new StringBuffer();
                if (null != appId && !"".equals(appId)) {
                    sbPath.append(appId);
                } else if (null != loginName && !"".equals(loginName)) {
                    //用户名首字母
                    sbPath.append("/");
                    sbPath.append(loginName.substring(0, 1).toLowerCase());
                    sbPath.append("/");
                    //用户名
                    sbPath.append(loginName);
                } else {
                    sbPath.append("other");
                }
                sbPath.append("/");
                //拼接文件类型
                sbPath.append(FileUtil.getFileType(file.getOriginalFilename()));
                sbPath.append("/");
                String userPath = sbPath.toString();
                String filedirPath = filePath + userPath;
                //判断文件夹是否存在，如果不存在就创建
                FileUtil.isExist(filedirPath);
                //获取文件后缀
                String suffix = FileUtil.getFileSuffix(file.getOriginalFilename());
                //生成唯一文件名
                String uuId = CodecUtil.UUID();
                String fileName = uuId + suffix;
                File tofile = new File(filedirPath + fileName);
                file.transferTo(tofile);
                if ("img".equals(FileUtil.getFileType(file.getOriginalFilename()))) {
                    //文件服务水印逻辑去掉
                    FileUtil.imagesResize(tofile, filedirPath);

                }
                FileStorageDto fileStorage = new FileStorageDto();
                fileStorage.setName(uuId);
                fileStorage.setFilename(file.getOriginalFilename());
                fileStorage.setUrl(userPath);
                if (null != description && !"".equals(description)) {
                    fileStorage.setDescription(description);
                }
                fileStorage.setSize(file.getSize());
                fileStorage.setSuffix(suffix);
                fileStorage.setUserName(loginName);
                //将上传文件信息存入数据库
                fileStorage = this.fileStorageService.save(fileStorage);
                if (null != fileStorage) {
                    //判断是否需要转换在线预览服务
                    if ("Y".equals(preViewFlag)) {
                        if ("doc".equals(FileUtil.getFileType(file.getOriginalFilename()))) {
                            fileService.preViewTask(fileServiceDownloadUrl, preViewServiceUrl,
                                    fileStorage.getName(), FileUtil.getFileSuffix(file.getName()));
                        }
                    }
                    Map<String, String> retMap = new HashMap<>();
                    retMap.put("filename", fileStorage.getFilename());
                    retMap.put("value", "/fms/api/show/" + fileStorage.getName() + "_0/" + fileStorage.getFilename());
                    retMap.put("url", "/fms/api/show/" + fileStorage.getName() + "_0/" + fileStorage.getFilename());
                    retMap.put("size", fileStorage.getSize().toString());
                    return ResultForAmis.success(retMap);
                } else {
                    return ResultForAmis.fail("信息存储失败");
                }
            }
        } else {
            return ResultForAmis.fail("上传文件不能为空");
        }


    }

    /**
     * 上传大文件
     *
     * @param param
     * @param request
     * @return
     * @throws IOException
     */
    @PostMapping("/upload/max")
    @ResponseBody
    public Result upload(FileUploadRequestParam param, HttpServletRequest request) throws IOException {
        //判断是否为Content-Type: multipart/form-data
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        FileUploadDTO fileUploadDTO = null;
        if (isMultipart) {
            StopWatch stopWatch = new StopWatch("上传性能监控");
            stopWatch.start("upload");
            if (param.getChunk() != null && param.getChunks() > 0) {
                //切片上传
                fileUploadDTO = fileService.sliceUpload(param);
            } else {
                //直接上传
                fileUploadDTO = fileService.upload(param);
            }
            stopWatch.stop();
            log.info("上传耗时{}ms", stopWatch.getTotalTimeMillis());
            Map<String, String> retMap = new HashMap<>();
            return Result.success(null, ResponseMsg.SUCCESS.getCode(), ResponseMsg.SUCCESS.getDesc(), fileUploadDTO);
        }
        throw new BizException("上传失败", ResponseMsg.ERROR.getCode());
    }

    /**
     * 查询文件信息
     *
     * @param fileIds
     * @return
     * @throws IOException
     */
    @PostMapping("/findFileByNames")
    @ResponseBody
    public Result findFileByNames(@RequestParam String fileIds){
        List<FileStorageDto> fileStorageModels = fileStorageService.findFileByNames(fileIds);
        return Result.success(null, ResponseMsg.SUCCESS.getCode(), ResponseMsg.SUCCESS.getDesc(), fileStorageModels);
    }


    /**
     * 根据md5查询文件
     *
     * @param md5
     * @param appId
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/checkFileMd5", method = RequestMethod.POST)
    @ResponseBody
    public Result checkFileMd5(String md5, String appId) throws IOException {

        FileUploadRequestParam param = new FileUploadRequestParam().setAppId(appId).setMd5(md5);
        FileUploadDTO fileUploadDTO = fileService.checkFileMd5(param);

        return Result.success(null, ResponseMsg.SUCCESS.getCode(), ResponseMsg.SUCCESS.getDesc(), fileUploadDTO);
    }

    /**
     * 根据图片名称展示图片
     *
     * @param fileName 文件名称
     * @param type     类型
     */
    @GetMapping(value = {"/show/{name}_{type}", "/show/{name}_{type}/{fileName}"})
    @ResponseBody
    public ResponseEntity<Resource> show(@PathVariable(value = "name") String fileName, @PathVariable String type, HttpServletRequest request) {
        Map<String, Object> result = new HashMap<String, Object>();
        String fileName_type = "";
        if (null != fileName && !"".equals(fileName)) {
            FileStorageDto fileStorageDto = fileStorageService.findByName(fileName);
            if (null != fileStorageDto) {

                if (null != type && !"0".equals(type) && !"1".equals(type)) {
                    fileName_type = fileName + "_" + type;
                } else {
                    fileName_type = fileName;
                }
                File file = new File(filePath + fileStorageDto.getUrl() + fileName_type + fileStorageDto.getSuffix());
                if (file.isFile() && file.exists()) {
                    Resource resource = fileStorageService.renderBinary(filePath + fileStorageDto.getUrl() + fileName_type + fileStorageDto.getSuffix());
                    String contentType = null;
                    try {
                        contentType = request.getServletContext().getMimeType(resource.getFile().getAbsolutePath());
                    } catch (IOException ex) {
                        log.info("Could not determine file type.");
                    }

                    // Fallback to the default content type if type could not be determined
                    if (contentType == null) {
                        contentType = "application/octet-stream";
                    }
                    return ResponseEntity.ok()
                            .contentType(MediaType.parseMediaType(contentType))
                            .header(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"" + resource.getFilename() + "\"")
                            .body(resource);

                } else {
                    fileName_type = fileName + "_m";
                    File filem = new File(filePath + fileStorageDto.getUrl() + fileName_type + fileStorageDto.getSuffix());
                    if (filem.isFile() && filem.exists()) {
                        Resource resource = fileStorageService.renderBinary(filePath + fileStorageDto.getUrl() + fileName_type + fileStorageDto.getSuffix());
                        String contentType = null;
                        try {
                            contentType = request.getServletContext().getMimeType(resource.getFile().getAbsolutePath());
                        } catch (IOException ex) {
                            log.info("Could not determine file type.");
                        }

                        // Fallback to the default content type if type could not be determined
                        if (contentType == null) {
                            contentType = "application/octet-stream";
                        }
                        return ResponseEntity.ok()
                                .contentType(MediaType.parseMediaType(contentType))
                                .header(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"" + resource.getFilename() + "\"")
                                .body(resource);

                    } else {
                        fileName_type = fileName + "_w";
                        File files = new File(filePath + fileStorageDto.getUrl() + fileName_type + fileStorageDto.getSuffix());
                        if (files.isFile() && files.exists()) {

                            Resource resource = fileStorageService.renderBinary(filePath + fileStorageDto.getUrl() + fileName_type + fileStorageDto.getSuffix());
                            String contentType = null;
                            try {
                                contentType = request.getServletContext().getMimeType(resource.getFile().getAbsolutePath());
                            } catch (IOException ex) {
                                log.info("Could not determine file type.");
                            }

                            // Fallback to the default content type if type could not be determined
                            if (contentType == null) {
                                contentType = "application/octet-stream";
                            }
                            return ResponseEntity.ok()
                                    .contentType(MediaType.parseMediaType(contentType))
                                    .header(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"" + resource.getFilename() + "\"")
                                    .body(resource);

                        } else {
                            File file0 = new File(filePath + fileStorageDto.getUrl() + fileName + fileStorageDto.getSuffix());
                            if (file0.isFile() && file0.exists()) {
                                Resource resource = fileStorageService.renderBinary(filePath + fileStorageDto.getUrl() + fileName + fileStorageDto.getSuffix());
                                String contentType = null;
                                try {
                                    contentType = request.getServletContext().getMimeType(resource.getFile().getAbsolutePath());
                                } catch (IOException ex) {
                                    log.info("Could not determine file type.");
                                }

                                // Fallback to the default content type if type could not be determined
                                if (contentType == null) {
                                    contentType = "application/octet-stream";
                                }
                                return ResponseEntity.ok()
                                        .contentType(MediaType.parseMediaType(contentType))
                                        .header(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"" + resource.getFilename() + "\"")
                                        .body(resource);
                            }
                        }
                    }
                }
            }
        }

        return ResponseEntity.status(Integer.parseInt(EcspConstants.FAIL)).body(null);
    }


    /**
     * 下载文件
     *
     * @param fileName 文件名
     */
    @GetMapping("/download/{name}")
    @ResponseBody
    public ResponseEntity<Resource> download(@PathVariable("name") String fileName, HttpServletRequest request) throws UnsupportedEncodingException {

        FileStorageDto fileStorageDto = fileStorageService.findByName(fileName);
        if (null == fileStorageDto) {
            return null;
        }
        String suffix = fileStorageDto.getSuffix();
        if (!suffix.startsWith(".")) {
            suffix = "." + suffix;
        }
        Resource resource;
        if (StringUtils.isNotEmpty(fileStorageDto.getMD5())) {
            //大文件
            String basePath = getBasePath();
            resource = fileStorageService.renderBinary(basePath + fileStorageDto.getUrl() + fileName + suffix);
        }else {
            resource = fileStorageService.renderBinary(filePath + fileStorageDto.getUrl() + fileName + suffix);

        }
        String contentType = null;
        try {
            contentType = request.getServletContext().getMimeType(resource.getFile().getAbsolutePath());
        } catch (IOException ex) {
            log.info("Could not determine file type.");
        }

        if (contentType == null) {
            contentType = "application/octet-stream";
        }
        String fileNameDown = new String(fileStorageDto.getFilename().getBytes("utf-8"), "ISO-8859-1");
        return ResponseEntity.ok()
                .contentType(MediaType.parseMediaType(contentType))
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + fileNameDown)
                .body(resource);
    }


    /**
     * 上传文件
     *
     * @param imageData   imageData字符串
     * @param loginName   上传用户登录名称
     * @param description 文件描述
     * @param appId       应用Id
     */
    @PostMapping("/uploadByBase64Data")
    @ResponseBody
    public Result uploadByBase64Data(String imageData, String loginName, String description, String isWaterMar, String appId, HttpServletResponse response) throws Exception {
        long sTime = System.currentTimeMillis();
        response.setContentType("text/html;charset=UTF-8");
        response.setHeader("Access-Control-Allow-Origin", "*");
//        if (null == appId || "".equals(appId)) {
//            renderEcspJson("", "fileStorage", FileConstants.FAIL, "appId不能为空");
//        }
        if (StringUtils.isNotEmpty(imageData)) {
            //图片后缀
            String ext = StringUtils.substringBetween(imageData, "data:image/", ";");
            if (StringUtils.isEmpty(ext)) {
                ext = "jpg";
            } else {
                if ("jpeg".equalsIgnoreCase(ext)) {//编码的jpeg图片数据
                    ext = "jpg";
                } else if ("x-icon".equalsIgnoreCase(ext)) {//编码的icon图片数据
                    ext = "ico";
                }
            }
            //图片数据
            String base64ImgData = StringUtils.substringAfter(imageData, "base64,");
            String filePath64 = fileBase64Path + CodecUtil.UUID() + "." + ext;
            ImageBase64Util.generateImage(base64ImgData, filePath64);
            log.info("generateImage {}ms", (System.currentTimeMillis() - sTime));
            File file = new File(filePath64);


            if (file.length() >= FileConstants.IMGSIZE) {
                log.info("上传文件超过限制大小");
                return Result.success("fileStorage", FileConstants.FILESIZE, "上传文件超过限制大小");
            } else {
                StringBuffer sbPath = new StringBuffer();
                if (null != appId && !"".equals(appId)) {
                    sbPath.append(appId);
                } else if (null != loginName && !"".equals(loginName)) {
                    //用户名首字母
                    sbPath.append("/");
                    sbPath.append(loginName.substring(0, 1).toLowerCase());
                    sbPath.append("/");
                    //用户名
                    sbPath.append(loginName);
                } else {
                    sbPath.append("other");
                }
                sbPath.append("/");
                //拼接文件类型
                sbPath.append(FileUtil.getFileType(file.getName()));
                sbPath.append("/");
                String userPath = sbPath.toString();
                String filedirPath = filePath + userPath;
                //判断文件夹是否存在，如果不存在就创建
                FileUtil.isExist(filedirPath);
                //获取文件后缀
                String suffix = FileUtil.getFileSuffix(file.getName());
                //生成唯一文件名
                String uuId = CodecUtil.UUID();
                String fileName = uuId + suffix;
                File tofile = new File(filedirPath + fileName);
                FileUtils.copyFile(file, tofile);
                if ("img".equals(FileUtil.getFileType(file.getName()))) {
/*                    if (null != isWaterMar && "0".equals(isWaterMar)) {
                        FileUtil.imagesResize(tofile, filedirPath);
                    } else {
                        FileUtil.imagesResizeWaterMark(tofile, filedirPath);
                    }*/
                    //文件服务水印逻辑去掉
                    FileUtil.imagesResize(tofile, filedirPath);

                }
                FileStorageDto fileStorage = new FileStorageDto();
                fileStorage.setName(uuId);
                fileStorage.setFilename(file.getName());
                fileStorage.setUrl(userPath);
                if (null != description && !"".equals(description)) {
                    fileStorage.setDescription(description);
                }
                fileStorage.setSize(file.length());
                fileStorage.setSuffix(suffix);
                fileStorage.setUserName(loginName);
                //将上传文件信息存入数据库
                fileStorage = fileStorageService.save(fileStorage);
                if (null != fileStorage) {
                    log.info("上传成功");
                    log.info("generateImage all {}ms", (System.currentTimeMillis() - sTime));
                    return Result.success("fileStorage", EcspConstants.SUCESS, "上传成功", fileStorage);
                } else {
                    log.info("信息存储失败");
                    return Result.success("fileStorage", FileConstants.STORAGEFAIL, "信息存储失败");
                }
            }
        } else {
            log.info("上传文件不能为空");
            return Result.success("fileStorage", FileConstants.FILENOTNULL, "上传文件不能为空");
        }


    }

    /**
     * 图片裁剪
     *
     * @param fileName 图片名称
     * @param x1       裁剪起始坐标x
     * @param y1       裁剪起始坐标y
     * @param x2       裁剪结束坐标x
     * @param y2       裁剪结束坐标y
     */
    @GetMapping("/cutImage/{fileName}/{x1}/{y1}/{x2}/{y2}/{zw}/{zh}")
    @ResponseBody
    public Map<String,Object> imagesCut(@PathVariable(value = "fileName") String fileName, @PathVariable(value = "x1") int x1,
                            @PathVariable(value = "y1") int y1, @PathVariable(value = "x2") int x2, @PathVariable(value = "y2") int y2,
                            @PathVariable(value = "zw") int zw,
                            @PathVariable(value = "zh") int zh) {
        Map<String, Object> result = new HashMap<String, Object>();
        String rtnCode = FileConstants.IMAGESCUTSUCCESS;
        String rtnMsg = "图片上传成功";
        FileStorageDto fStorage = fileStorageService.findByName(fileName);
        if (null != fStorage) {
            String url = fStorage.getUrl();
            String suffix = fStorage.getSuffix();
            String originalFilename = fStorage.getFilename();
            String userName = fStorage.getUserName();
            //获取源文件
            log.info("file path:{}",filePath + url + fileName + suffix);
            File file = new File(filePath + url + fileName + suffix);
            log.info("file:{}",file);
            File zfile = new File(filePath + url + fileName + "_z" + suffix);
            //生成目标文件
            String uuid = CodecUtil.UUID();
            File toFile = new File(filePath + url + uuid + suffix);
            //裁剪图片
            Images.resize(file, zfile, zw, zh);
            Images.crop(zfile, toFile, x1, y1, x2, y2);
            //删除原文件
            fileStorageService.delete(fileName);
            //获取源文件
            File file_c = new File(filePath + url + fileName + "_c" + suffix);
            File file_s = new File(filePath + url + fileName + "_s" + suffix);
            File file_m = new File(filePath + url + fileName + "_m" + suffix);
            //删除原文件
            file.delete();
            file_c.delete();
            file_s.delete();
            file_m.delete();
            zfile.delete();

            //  Logger.info("裁剪成功");
            //---------------------add by furq start 生成不同规格的图片

            String fileDirPath = filePath + url;
            if ("img".equals(FileUtil.getFileType(file.getName()))) {
                FileUtil.imagesResize(toFile, fileDirPath);
            }
            //---------------------add by furq end 生成不同规格的图片
            FileStorageDto fileStorage = new FileStorageDto();
            fileStorage.setName(uuid);
            fileStorage.setFilename(originalFilename);
            fileStorage.setUrl(url);
            fileStorage.setSize(file.length());
            fileStorage.setSuffix(suffix);
            fileStorage.setUserName(userName);
            //将上传文件信息存入数据库
            fileStorage = this.fileStorageService.save(fileStorage);
            if (null != fileStorage) {
                result.put("rtnData", fileStorage);
            } else {
                rtnCode = FileConstants.STORAGEFAIL;
                rtnMsg = "信息保存失败";
            }
        } else {
            rtnCode = FileConstants.IMAGESCUTFALL;
            rtnMsg = "图片裁剪失败";
        }
        result.put("rtnCode", rtnCode);
        result.put("rtnMsg", rtnMsg);
        return result;
    }

    private String getBasePath() {
        String path = uploadRootDir;
        if (SystemUtil.isWinOs()) {
            path = uploadWindowRoot + uploadRootDir;
        }

        return path;
    }
}
